/*
 * Linux IEEE 802.15.4 6lowpan adaptation layer
 *
 * Copyright (C) 2010 HIIT
 *
 * Written-by: Dmitry Kuptsov
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
 
#include "6lowpan_dev.h"

#define SELECT_TIMOUT_USEC 100

//Opens and configures TUN device:
//Assign with IPv6 address:
//Prefix part: 64 bit network preffix
//Host address part: 64 bit long MAC address of 802.15.4 network interface
int open_and_config_tun(const lowpan_device_t const * dev) {
	return 0;
}

//Opens and configures 802.15.4 device:
int open_and_config_lowpan(lowpan_device_t * dev) {
	//more configuration needed
	return socket(PF_IEEE802154, SOCK_RAW, 0);
}

//Main protocol loop...
//Receives packets from TUN -> adapts for 802.15.4 and reinjects:
//		- fragments
//		- computes routes (advanced features)
//		- compresses headers
//		- handles neigbor discovery requests
//Receives packets from 802.15.4 -> reinjects into 802.15.4:
//		- reassembles fragmented packets
//		- decompresses headers
//		- handles neigbor discovery requests
int protocol_loop(int router_mode) {
	memset(&device, 0, sizeof(lowpan_device_t));
	int lsd = open_and_config_lowpan(&device); //6lowpan socket descriptor
	int tsd = open_and_config_tun(&device);

	fd_set rx;

	struct timeval select_timeout;	
	select_timeout.tv_sec = 0;
	select_timeout.tv_usec =  SELECT_TIMOUT_USEC;

	int highest_descriptor = (lsd > tsd ? lsd : tsd) + 1;

	while (1) {
		//DO NORMAL SOCKET READ/WRITE STUFF HERE 
		FD_ZERO(&rx);
		FD_SET(lsd, &rx);	
		FD_SET(tsd, &rx);
	
		err = select(highest_descriptor, &rx,
                     NULL, NULL, &select_timeout);
		if (err < 0) {
			goto maintenance;
		} else if (err == 0) {
			/* idle cycle - select() timeout */
			goto maintenance;
		}	

		if (FD_ISSET(lsd, &rx)) {
			//Something to read from the 802.15.4 device			
		} else if(FD_ISSET(tsd, &rx)) {
			//Something to read from the dummy device
		}
maintenance:		
	}
out_err:
	return 0;
}
